package cn.jiyun.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//自定义的全局拦截器
//判断请求的参数中是否有user=lucy如果没有就禁止访问
@Order(-1)//设置拦截器的优先级，值越小优先程度越高
@Component//组件
public class AuthorizeFilter implements GlobalFilter {

    //重写filter方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1获取请求的参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();

        //2获取user
        String user = params.getFirst("user");

        //3判断user的值是否为lucy
        if ("lucy".equals(user)){
            //放行
            return chain.filter(exchange);
        }
        //4拦截
            //1.设置拦截的状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            //2结束

        return exchange.getResponse().setComplete();//设置完成
    }
}